import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import qs from 'qs'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers = {
      // 配置请求头
    }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    if (config.method === 'get') {
      config.paramsSerializer = function(params) {
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 1.接收到响应数据并成功后的一些共有的处理，关闭loading等
    return response
  },
  error => {
    if (error && error.response) {
      // 1.公共错误处理
      // 2.根据响应码具体处理
      switch (error.response.status) {
        case 403:
          MessageBox.alert(error.response.data, '登录失效', {
            confirmButtonText: '重新登录',
            type: 'warning',
            callback: () => {
              removeToken()
              location.reload()
            }
          })
          return error
        case 401:
          error.message = error.response.data
          break
        case 409:
          error.message = error.response.data
          break
        case 415:
          error.message = '服务器开小差啦，请稍候重试'
          break
        case 500:
          error.message = '服务器端出错'
          break
        default:
          error.message = `连接错误${error.response.status}`
      }
    } else {
      error.message = '连接服务器失败'
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return error
  }
)

export default service
